/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;  
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;  
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.primefaces.component.graphicimage.GraphicImage;
import org.primefaces.event.CaptureEvent;
import org.primefaces.model.DefaultStreamedContent;
/**
 *
 * @author iron
 */
@ManagedBean(name="photoCamMBean") 
public class PhotoCamBean {
    File f;
    DefaultStreamedContent file;    
    InputStream stream;
    private String photo; 
    int i = 0;
    ByteArrayInputStream bais;
    org.primefaces.event.CaptureEvent captureEvent;
    public GraphicImage img; 
    public synchronized void capture(org.primefaces.event.CaptureEvent captureEvent) {  
       this.captureEvent = captureEvent;
       BufferedImage img;
       bais = new ByteArrayInputStream(captureEvent.getData());         
       try {            
            img = ImageIO.read(bais);
            bais.close();
            f = new File("/home/iron/Área de Trabalho/Foto/"+new Date().getTime()+".png");
            saveImageFile(img, f);
            photo = f.getAbsolutePath();
            System.out.println(f.getAbsolutePath());
            Toolkit.getDefaultToolkit().beep();
            
        } catch (Exception ex) {
            Logger.getLogger(PhotoCamBean.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Entrou!");
        }         
    }

    public String getPhoto(){
        return photo;
    }

    public GraphicImage getImg() {
        return img;
    }

    public void setImg(GraphicImage img) {
        this.img = img;
    }
    
    public DefaultStreamedContent getFile() { 
        try{
        return new DefaultStreamedContent(new ByteArrayInputStream(captureEvent.getData()) , "image/png","yourPhoto"); 
        }catch(Exception ex){
         return   new DefaultStreamedContent(FacesContext.getCurrentInstance()
                                            .getExternalContext().getResourceAsStream("imagens/branco.png"));
        }} 
    
    public synchronized void downloadFile(){
        downloadFile(f.getName(), f.getPath(), "png", FacesContext.getCurrentInstance());
    }
    
    public synchronized void saveImageFile(BufferedImage img, File f){
        
        String nomeCompleto = "";
        try{
        nomeCompleto = f.getAbsolutePath();
        }catch(Exception ex){return;}
        
        try {
            //System.out.println(nomeCompleto.substring(nomeCompleto.length()-3));
            ImageIO.write(img, nomeCompleto.substring(nomeCompleto.length()-3), new File(nomeCompleto));
            
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        System.out.println("Imagem salva! "+f.getAbsolutePath());
    }

   
    
    public static synchronized void downloadFile(String filename, String fileLocation, String mimeType,  
                                                 FacesContext facesContext) {  
  
        ExternalContext context = facesContext.getExternalContext(); // Context  
        String path = fileLocation; // Localizacao do arquivo  
        String fullFileName = path + filename;  
        File file = new File(path); // Objeto arquivo mesmo :)  
  
        HttpServletResponse response = (HttpServletResponse) context.getResponse();  
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\""); //aki eu seto o header e o nome q vai aparecer na hr do donwload  
        response.setContentLength((int) file.length()); // O tamanho do arquivo  
        response.setContentType(mimeType); // e obviamente o tipo  
  
        try {  
            FileInputStream in = new FileInputStream(file);  
            OutputStream out = response.getOutputStream();  
  
            byte[] buf = new byte[(int)file.length()];  
            int count;  
            while ((count = in.read(buf)) >= 0) {  
                out.write(buf, 0, count);  
            }  
            in.close();  
            out.flush();  
            out.close();  
        facesContext.responseComplete();  
        } catch (IOException ex) {  
            System.out.println("Error in downloadFile: " + ex.getMessage());  
            ex.printStackTrace();  
        }  
    }  
    
}

